/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.aeso.betabit.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

/**
 *
 * @author Edson
 */
public abstract class JPAHelper {

    private EntityManagerFactory factory;

    public JPAHelper(EntityManagerFactory factory) {
        this.factory = factory;
    }

    public void execute() {
        EntityManager manager = null;
        EntityTransaction transaction = null;

        try {
            manager = factory.createEntityManager();
            transaction = manager.getTransaction();

            transaction.begin();

            execute(manager);

            manager.flush();

            transaction.commit();
        } catch (RuntimeException exception) {

            if (transaction != null) {
                try {
                    transaction.rollback();
                } catch (RuntimeException e) {
                }
            }
            throw exception;
        } finally {
            manager.close();
        }
    }

    protected abstract void execute(EntityManager manager);
}